package com.cf_houduan.cf_houduan.constant;

import com.cf_houduan.cf_houduan.enums.CodeAndMsgEnum;
import com.cf_houduan.cf_houduan.util.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class UniformReponseHandler {

    @ResponseStatus(HttpStatus.OK)
    public Result sendSuccessResponse(){
        return new Result(CodeAndMsgEnum.SUCCESS.getCode(), CodeAndMsgEnum.SUCCESS.getName(), null);
    }

    @ResponseStatus(HttpStatus.OK)
    public Result sendSuccessResponse(Object data) {
        return new Result(CodeAndMsgEnum.SUCCESS.getCode(), CodeAndMsgEnum.SUCCESS.getName(), data);
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result sendErrorResponse_UserDefined(Exception exception){
        return new Result(CodeAndMsgEnum.FAIL.getCode(), ((BusinessException)exception).getMessage(), null);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result sendErrorResponse_System(Exception exception){
        if (exception instanceof BusinessException) {
            return this.sendErrorResponse_UserDefined(exception);
        }

        return new Result(CodeAndMsgEnum.EXCEPTION.getCode(),CodeAndMsgEnum.EXCEPTION.getName(), null);
    }

}
